from playwright.sync_api import sync_playwright, Request, Response


class CardActivatorSync:
    def __init__(self):
        self.playwright = sync_playwright().start()
        self.browser = self.playwright.chromium.launch(
            headless=False, slow_mo=2000)
        self.page = self.browser.new_page()
        self.response_data = None

        # 设置请求和响应的回调
        self.page.on("request", self.on_request)
        self.page.on("response", self.on_response)

    def on_request(self, request: Request) -> None:
        pass

    def on_response(self, response: Response) -> None:
        if "activate-gift-coupon" in response.url:
            # print("response status", response.status)
            content_type = response.headers.get("content-type")
            # print("response content-type", content_type)
            # print("url---->", response.url)
            if response.status == 200 and content_type and "application/json" in content_type:
                self.response_data = response.json()
                # print("response json", self.response_data, type(self.response_data))

            else:
                self.response_data = response.text()
                # print("response text", self.response_data)

    def activate_card(self, name: str, mobile: str, id_number: str, code: str):
        url = f'''
        https://gljm.ytsjq.com/wapmall/index.html?m_code=dwr1Op9C3C5qVSng3ZWSFA#/pages/preview/preview?id={code}&type=5
        '''
        self.page.goto(url)
        self.page.locator(':text("我已知晓")').click()

        input_count = self.page.locator("input").count()
        self.page.locator("input").nth(0).fill(name)
        self.page.locator("input").nth(1).fill(id_number)
        self.page.locator("input").nth(2).fill(mobile)
        print("input_count", input_count)
        self.page.locator(':text("立即激活")').click()

    def close(self):
        self.browser.close()
        self.playwright.stop()

    def get_response_data(self):
        return self.response_data


# def main():
#     activator = CardActivator()
#     activator.activate_card(
#         name="尤伟",
#         mobile="15136107396",
#         id_number="410305196507294514",
#         code="1a81f073643813cbfc8102ccb388441e"
#     )
#     response_data = activator.get_response_data()
#     print("Response Data:", response_data)
#     activator.close()


if __name__ == "__main__":
    main()
